import { reactive } from 'vue'

class Store {
  constructor() {
    this.state = reactive({
      favorites: []
    })
    
    this.loadFavorites()
  }
  
  loadFavorites() {
    const favorites = localStorage.getItem('favorites')
    if (favorites) {
      this.state.favorites = JSON.parse(favorites)
    }
  }
  
  saveFavorites() {
    localStorage.setItem('favorites', JSON.stringify(this.state.favorites))
  }
  
  addFavorite(movieId) {
    if (!this.state.favorites.includes(movieId)) {
      this.state.favorites.push(movieId)
      this.saveFavorites()
    }
  }
  
  removeFavorite(movieId) {
    const index = this.state.favorites.indexOf(movieId)
    if (index > -1) {
      this.state.favorites.splice(index, 1)
      this.saveFavorites()
    }
  }
  
  isFavorite(movieId) {
    return this.state.favorites.includes(movieId)
  }
  
  getFavorites() {
    return [...this.state.favorites]
  }
}

export default new Store()